package cn.feizhu.aimarket.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.feizhu.aimarket.common.BaseResponse;
import cn.feizhu.aimarket.common.ResultUtils;
import cn.feizhu.aimarket.ratelimit.annotation.RateLimit;
import cn.feizhu.aimarket.ratelimit.enums.RateLimitType;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RedissonClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/test")
public class TestRateLimitController {

    @Resource
    private RedissonClient redissonClient;

    /**
     * 测试限流功能 - 每分钟最多3次
     */
    @SaCheckLogin
    @RateLimit(key = "test.download", limitType = RateLimitType.USER, rate = 3, rateInterval = 1, timeUnit = TimeUnit.MINUTES, message = "测试限流：每分钟最多3次")
    @GetMapping("/rate-limit")
    public BaseResponse<Map<String, Object>> testRateLimit() {
        Map<String, Object> result = new HashMap<>();
        result.put("message", "测试成功，限流正常工作");
        result.put("timestamp", System.currentTimeMillis());
        
        log.info("测试限流接口被调用");
        return ResultUtils.success(result);
    }

    /**
     * 查看限流器状态
     */
    @SaCheckLogin
    @GetMapping("/rate-limit-status")
    public BaseResponse<Map<String, Object>> getRateLimitStatus() {
        String key = "rate_limit:test.download:user:" + cn.dev33.satoken.stp.StpUtil.getLoginIdAsLong();
        RRateLimiter rateLimiter = redissonClient.getRateLimiter(key);
        
        Map<String, Object> result = new HashMap<>();
        result.put("key", key);
        result.put("availablePermits", rateLimiter.availablePermits());
        result.put("config", rateLimiter.getConfig());
        
        return ResultUtils.success(result);
    }
}